<!-- 科室下拉框 -->
<template>
  <px-form-item
    :label="customLabel || '科室'"
    prop="className"
    :rules="{ required: props.isRequired, message: '科室不能为空', trigger: ['blur', 'change'] }"
  >
    <px-select
      v-model="classNameVal"
      :disabled="props.isDisabled"
      :clearable="isClear || (classNameList && classNameList.length > 1)"
      filterable
      placeholder="请选择科室"
      style="width: 100%"
      @change="changeClassName"
      @clear="clear"
    >
      <px-option v-for="item in classNameList" :key="item.code" :label="item.name" :value="item.code" />
    </px-select>
  </px-form-item>
</template>

<script setup lang="ts">
import { ref, watch } from "vue";

// 父级方法和值
const emits = defineEmits(["changeClassName", "clear"]);
const props = defineProps(["className", "isRequired", "isDisabled", "noDefault", "customLabel", "isClear"]);

const classNameVal = ref("");
const classNameList = JSON.parse(localStorage.getItem("classList"));

watch(
  () => props.className,
  val => {
    setTimeout(async () => {
      if (classNameList && classNameList.length === 1 && !props.noDefault) {
        classNameVal.value = classNameList[0]?.code;
        emits("changeClassName", classNameVal.value, true);
      } else {
        classNameVal.value = props.className;
      }
    }, 0);
  },
  { immediate: true }
);
// 改变科室值，传值给父级并做改变
const changeClassName = () => {
  // 是否只有1个className值
  emits("changeClassName", classNameVal.value, false);
};
const clear = () => {
  emits("clear", classNameVal.value);
};
</script>
